         <style lang="less">
@import "./percentSet.less";
</style>
<template>
  <div>
    <div class="search" id="supplierManagePage" v-show="supplierManagePageVisible" style="width: 470px;float:left">
        <Row>
            <Col>
                <Card>
                    <Row>
                        <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
                            <Form-item label="商户名称" prop="supplierName">
                              <Input type="text" v-model="searchForm.supplierName" clearable placeholder="请输入商户名称" style="width: 150px"/>
                            </Form-item>
                            <Form-item label="手机号码" prop="mobile">
                              <Input type="text" v-model="searchForm.mobile" clearable placeholder="请输入手机号码" style="width: 150px"/>
                            </Form-item>
                            <Form-item style="margin-left:-35px;">
                              <Button @click="handleSearch" type="primary" icon="search">搜索</Button>
                              <Button @click="handleReset" type="ghost" icon="refresh">重置</Button>
                            </Form-item>
                        </Form>
                    </Row>
                    <Row class="margin-top-10 searchable-table-con1">
                        <Table :loading="loading" border :columns="columns" :data="data" sortable="custom" @on-sort-change="changeSort" @on-selection-change="showSelect" ref="table" @on-row-click="viewSupplierProduct" :highlight-row=true></Table>
                        <Table :columns="columns" :data="exportData" ref="exportTable" style="display:none"></Table>
                    </Row>
                    <Row type="flex" justify="end" class="code-row-bg page">
                        <Page :current="this.searchForm.pageNumber" :total="total" :page-size="this.searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50,100]" size="small" show-total show-elevator show-sizer></Page>
                    </Row>
                </Card>
            </Col>
        </Row>
    </div>

    <div class="search" style="width: 1220px;float:left;background:#ffffff;margin-left:10px;">
      <Tabs type="card">
        <TabPane label="线路活动" style="border-left: 1px solid #dddee1;height:680px;">
          <line-view ref="lineView" :supplierId="currentSupplierId" @on-open-success="openDistributeSuccess"
            @on-close-success="closeDistributeSuccess" @on-percentset-success="onPercentSetSuccess"></line-view>
        </TabPane>
        <TabPane label="客栈">
          <hotel-view ref="hotelView" :supplierId="currentSupplierId" @on-open-success="openDistributeSuccess"
            @on-close-success="closeDistributeSuccess" @on-percentset-success="onPercentSetSuccess"></hotel-view>
        </TabPane>
        <TabPane label="特产">
          <specialty-view ref="specialtyView" :supplierId="currentSupplierId" @on-open-success="openDistributeSuccess"
          @on-close-success="closeDistributeSuccess" @on-percentset-success="onPercentSetSuccess"></specialty-view>
        </TabPane>
        <TabPane label="通用商品">
          <goods-view ref="goodsView" :supplierId="currentSupplierId" @on-open-success="openDistributeSuccess"
          @on-close-success="closeDistributeSuccess" @on-percentset-success="onPercentSetSuccess"></goods-view>
        </TabPane>
      </Tabs>
    </div>

    <div class="search" id="supplierDetailPage" v-show="supplierDetailPageVisible" style="background-color:white;padding:20px;">
      <!-- <goods-detail ref="supplierDetailComp" @on-goods-cancel="goodsDetailCancel" @on-goods-success="goodsSubmitSuccess"></goods-detail> -->
      <!-- <supplier-detail ref="supplierDetailComp"
        @on-supplier-cancel="supplierDetailCancel"
        @on-supplier-success="supplierSubmitSuccess"
        @on-supplier-review-success="supplierReviewSuccess">
      </supplier-detail> -->
    </div>

    <percent-set-modal ref="percentSetModal" @on-set-success="percentSetSuccess"></percent-set-modal>

  </div>
</template>

<script>

import dateFormatUtil from "@/utils/dateFormatUtil";
import * as constants  from './constants';

import LineView from "./lineView.vue";
import HotelView from "./hotelView.vue";
import SpecialtyView from "./specialtyView.vue";
import GoodsView from "./goodsView.vue";

import PercentSetModal from "./percentSetModal.vue";

export default {
  name: "distrib-percent-set",
  components: {
    // SupplierDetail,
    // ReviewModal,
    LineView,
    HotelView,
    SpecialtyView,
    GoodsView,
    PercentSetModal
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码长度不得小于6位"));
      } else {
        callback();
      }
    };
    const validateMobile = (rule, value, callback) => {
      var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    const validatesupplierNameNoBlank = (rule, value, callback) => {
      var validObj = rule.validObj;
      // var reg = /\s+/g;  //注意：正则规则不带引号 所以对象中传入也不能带引号
      // var reg = new RegExp(/\s+/g); //不使用new RegExp 时灵时不灵
      var reg = new RegExp(validObj.regexp);
      if (reg.test(value)) {
        callback(new Error(validObj.msg));
      } else {
        callback();
      }
    };
    return {
      loading: true,
      drop: false,
      dropDownContent: "展开",
      dropDownIcon: "chevron-down",
      selectCount: 0,
      selectList: [],
      searchForm: {
        account: "",
        supplierName: "",
        linkMan: "",
        mobilePhone: "",
        email: "",
        qq: "",
        status: "",
        pageNumber: 1,
        pageSize: 10,
        sort: "createTime",
        order: "desc",
        startDate: "",
        endDate: "",
        province: "",
        city: "",
        area: "",
        street: ""
      },
      accountDisabled: false,
      // supplierFormAddressArr: ['云南省', '大理白族自治州', '大理市', '下关镇'],
      // supplierFormAddressArr: ['530000', '532900', '532901', '532901101000'],
      // supplierFormAddressArr: [],
      modalType: 0,
      supplierModalVisible: false,
      modalTitle: "",
      supplierForm: {
        supplierType: 0,
        supplierFormAddressArr: [],
        province: "",
        city: "",
        area: "",
        street: ""
      },
      province: "",
      city:"",
        // supplierFormAddressArr:[ this.supplierForm.province, this.supplierForm.city, this.supplierForm.area, this.supplierForm.street],
      userRoles: [],
      roleList: [],
      errorPass: "",
      supplierFormValidate: {
        account: [
          { required: true, message: "商户账号不能为空", trigger: "blur" },
          { max: 64, message: '商户账号太长'}
          // ,{ validator: validatesupplierNameNoBlank, validObj:{regexp:/\s+/g,msg:"商户账号不允许包含空格"} ,trigger: "blur"}
        ],
        supplierName: [
          { required: true, message: "商户名称不能为空", trigger: "blur" },
          { max: 64, message: '商户名称太长'},
          { validator: validatesupplierNameNoBlank, validObj:{regexp:/\s+/g,msg:"商户名称不允许包含空格"} ,trigger: "blur"}
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符'}
        ]
      },
      submitLoading: false,
      columns: [
        {
          title: "名称",
          key: "supplierName",
          width: 150,
          sortable: true
        },
        {
          title: "手机",
          key: "mobile",
          width: 140,
          sortable: true
        },
        {
          title:"商户分类",
          key:"supplierType",
          width:144,
          sortable: true,
          render: (h, params) => {
            if (params.row) {
              if (params.row.supplierType === 0){
                return h("span",
                  "普通商户"
                );
              }else{
                return h("span",
                  "达人商户"
                );
              }
            }
          }
        }
      ],
      data: [],
      exportData: [],
      total: 0
      ,
      isShowReviewModal: false,
      reviewStatus: "-1",
      reviewModalTitle: "",

      supplierReviewModalVisible: false,
      reviewModalTitle: "",
      supplierReviewForm: {
        reviewSupplierId: "",
        reviewStatus: "0",
        nopassReason: "",
        nopassReasonVisible: false
      },
      supplierReviewFormValidate: {
      },

      supplierManagePageVisible: true,
      supplierDetailPageVisible: false,

      //supplier-products start
      supplierProductsPageVisible: false,
      currentSupplierId: ""
      //supplier-products end

      ,currDisObj:{}


    };
  },

  methods: {

    openDistributeSuccess:function(res){
      if(res.flag){

        let disObj = this.parseOpenDisObj(res, 1);
        this.currDisObj = disObj;

        this.$Modal.confirm({
          title: "确认开启分销",
          content: "您确认要开启分销 " + disObj.title + " ?",
          onOk: () => {
            this.putRequest(disObj.url, disObj.params).then(res => {
              if (res.success === true) {
                this.$Message.success("开启分销成功");
                this.refreshTable();
                // this.init();
              }
            });
          }
        });
      }
    },

    closeDistributeSuccess:function(res){
      if(res.flag){

        let disObj = this.parseOpenDisObj(res, 0);
        this.currDisObj = disObj;

        this.$Modal.confirm({
          title: "确认关闭分销",
          content: "您确认要关闭分销 " + disObj.title + " ?",
          onOk: () => {
            this.putRequest(disObj.url, disObj.params).then(res => {
              if (res.success === true) {
                this.$Message.success("关闭分销成功");
                this.refreshTable();
                // this.init();
              }
            });
          }
        });
      }
    },

    percentSetSuccess(res){
      if(res.flag){
        this.refreshTable(res.type);
      }
    },

    // type参数主要兼容percentSetSuccess返回
    refreshTable(refreshType){
      console.log("========refreshTable=========");
      let type = this.currDisObj.type || refreshType;
      let currSupplierId = this.currentSupplierId;
      if(type=="LINE"){
        this.$refs.lineView.transSupplierId(currSupplierId);
      }else if(type=="HOTEL"){
        this.$refs.hotelView.transSupplierId(currSupplierId);
      }else if(type=="SPECIAL"){
        this.$refs.specialtyView.transSupplierId(currSupplierId);
      }else if(type=="GOODS"){
        this.$refs.goodsView.transSupplierId(currSupplierId);
      }else{}
    },

    parseOpenDisObj(res, operateType){
      let type = res.type;
      let disObj = res.disObj;

      let openDisObj = {};
      let operType = '';
      (operateType === 1) ? operType = 'open' : operType = 'close';
      if(type=="LINE"){
        openDisObj = this.constructOpenDisObj(type, "/line/"+operType, disObj.title, disObj);
      }else if(type=="HOTEL"){
        openDisObj = this.constructOpenDisObj(type, "/hotel/"+operType, disObj.title, disObj);
      }else if(type=="SPECIAL"){
        openDisObj = this.constructOpenDisObj(type, "/goods/"+operType, disObj.goodsName, disObj);
      }else if(type=="GOODS"){
        openDisObj = this.constructOpenDisObj(type, "/goods_item/"+operType, disObj.itemName, disObj);
      }else{}

      return openDisObj;
    },

    constructOpenDisObj(type, url, title, disObj){
      let returnDisObj = {};

      returnDisObj.type = type;
      returnDisObj.url = url;
      returnDisObj.title = title;

      returnDisObj.params ={};
      returnDisObj.params.ids = disObj.id;
      // returnDisObj.params.isDistribut = 1;
      // (!disObj.billRow)&&(disObj.billRow=0);
      // returnDisObj.params.billRow = disObj.billRow;

      return returnDisObj;
    },


    onPercentSetSuccess:function(res){
      if(res.flag){
        console.log("=========onPercentSetSuccess=========");

        let disObj = res.disObj;
        var disSetObj={
          type: res.type,
          id: disObj.id,
          title: "分销比例设置",
          billRow: disObj.billRow * 100
        }
        this.$refs.percentSetModal.openSetModal(true,disSetObj);

      }
    },

    init() {
      this.getSupplierList();
      this.cleanSelectCount();
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getSupplierList();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getSupplierList();
    },
    selectDateRange(v) {
      if (v) {
        this.searchForm.startDate = v[0];
        this.searchForm.endDate = v[1];
      }
    },

    getSupplierList() {
      this.loading = true;
      this.getRequest("/supplier/list", this.searchForm).then(res => {
        this.loading = false;
        if (res.success === true) {
          console.log("listres:",res)
          this.data = res.result.content;
          this.total = res.result.totalElements;
        }
      });
    },
    handleSearch() {
      // console.log(this.resArr);
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.init();
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      // 重新加载数据
      this.init();
    },
    changeSort(e) {
      this.searchForm.sort = e.key;
      this.searchForm.order = e.order;
      if (e.order === "normal") {
        this.searchForm.order = "";
      }
      this.init();
    },

    cancelsupplier() {
      this.supplierModalVisible = false;
    },

    review(v) {
      let editSupplierId = v.id;
      this.loading = true;
      this.postRequest("/supplier/query/" + v.id ).then(res =>{
        this.loading = false;
        console.log(res.result);
        let updateSupplier = res.result;

        this.$refs.supplierDetailComp.resetFormByType(2, updateSupplier);
        //切换界面显示隐藏
        this.supplierManagePageVisible = false;
        this.supplierDetailPageVisible = true;
      })
    },

    supplierRevewStatusChange(value) {
      (value === "-1") ? (this.supplierReviewForm.nopassReasonVisible = true) : (this.supplierReviewForm.nopassReasonVisible = false);
    },
    cancelSupplierReview() {
      this.supplierReviewModalVisible = false;
    },
    submitSupplierReview() {
      let url = "";
      url = "/supplier/review";
      let reviewSupplier = {};
      reviewSupplier.id = this.supplierReviewForm.reviewSupplierId;
      reviewSupplier.status = this.supplierReviewForm.reviewStatus;
      reviewSupplier.reason = this.supplierReviewForm.nopassReason;
      console.log("==================");
      console.log(reviewSupplier);
      this.submitLoading = true;
      this.putRequest(url, reviewSupplier).then(res => {
        this.submitLoading = false;
        if (res.success === true) {
          this.$Message.success("审核操作成功");
          this.init();
          this.supplierReviewModalVisible = false;
        }
      });

      // 暂未做验证
      // this.$refs.hotelReviewForm.validate(valid => {
      //   if (valid) {
      //   }
      // });
    },

    supplierDetailCancel:function(v){
      if(v){
        this.supplierManagePageVisible = true;
        this.supplierDetailPageVisible = false;
      }
    },
    supplierSubmitSuccess: function(v){
      this.successShow(v);
    },
    supplierReviewSuccess: function(v){
      this.successShow(v);
    },
    successShow: function(v){
      if(v){
        this.supplierManagePageVisible = true;
        this.supplierDetailPageVisible = false;
        this.getSupplierList();
      }
    },

    enable(v) {
      this.$Modal.confirm({
        title: "确认启用",
        content: "您确认要启用商户 " + v.supplierName + " ?",
        onOk: () => {
          console.log("id",v.id)
          this.postRequest("/supplier/enable/" + v.id).then(res => {
            console.log("res:",res)
            if (res.success === true) {
              this.$Message.success("操作成功");
              this.init();
            }
          });
        }
      });
    },
    disable(v) {
      this.$Modal.confirm({
        title: "确认禁用",
        content: "您确认要禁用商户 " + v.supplierName + " ?",
        onOk: () => {
          this.postRequest("/supplier/disable/" + v.id).then(res => {
            if (res.success === true) {
              this.$Message.success("操作成功");
              this.init();
            }
          });
        }
      });
    },

    dropDown() {
      if (this.drop) {
        this.dropDownContent = "展开";
        this.dropDownIcon = "chevron-down";
      } else {
        this.dropDownContent = "收起";
        this.dropDownIcon = "chevron-up";
      }
      this.drop = !this.drop;
    },
    showSelect(e) {
      this.exportData = e;
      this.selectList = e;
      this.selectCount = e.length;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
      this.cleanSelectCount();
    },
    cleanSelectCount(){
      this.selectCount = 0;
    },


    // 点击查看供应商所有数据
    viewSupplierProduct:function(v){
      this.supplierProductsPageVisible = true;
      this.currentSupplierId = v.id;
      console.log("this.currentSupplierId:",this.currentSupplierId);
      this.$refs.lineView.transSupplierId(v.id);
      this.$refs.hotelView.transSupplierId(v.id);
      this.$refs.specialtyView.transSupplierId(v.id);
      this.$refs.goodsView.transSupplierId(v.id);


      // 注意以下方法不带分页
      // this.loading = true;
      // this.getRequest("/supplier/getMap",this.currentSupplierId).then(res => {
      //   this.loading = false;
      //   if (res.success === true) {
      //     let lineList = res.result.lineList;
      //     let hotelList = res.result.hotelList;
      //     let goodsList = res.result.goodsList;
      //     let goodsItemList = res.result.goodsItemList;
      //     this.$refs.lineview.initLineData(lineList);
      //   }
      // });

    }


  },
  mounted() {
    console.log("=================mounted====================");
    console.log("===========columns============");
    console.log(this.columns);
    // console.log(constants.ADD_ARTICLE_LIST);

    this.init();
    // this.getRoleList();
  }
};
</script>
